package meth

import (
	"bufio"
	"bytes"
	"io"
	"net/http"
	"regexp"
	"strings"
	"time"
)

type DeviceInfo struct {
	FirmwareVersion string
	DeviceID        string
}

func parseDeviceInfo(content string) DeviceInfo {
	return DeviceInfo{
		FirmwareVersion: extractValue(content, "firmware_version"),
		DeviceID:        extractValue(content, "device_id"),
	}
}

func FetchVersion(ip string) (string, DeviceInfo) {
	client := &http.Client{
		Timeout: 1 * time.Second,
	}

	resp, err := client.Get("http://" + ip)
	if err != nil {
		return "", DeviceInfo{}
	}
	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		return "", DeviceInfo{}
	}
	// 读取完整响应体
	fullContent, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", DeviceInfo{}
	}

	if !validateLine(fullContent) {
		return "", DeviceInfo{}
	}

	return "AI-VOICE-Z01", parseDeviceInfo(string(fullContent))
}

// extractValue 通用HTML属性值提取函数
func extractValue(content string, id string) string {
	// 优化后的正则表达式，允许属性顺序变化
	pattern := `<input\s+[^>]*?id=["']` + id + `["'][^>]*?value=["']([^"']*)["']`
	//pattern := `(?si)<input[^>]*?id\s*=\s*['"]?` + id + `['"]?[^>]*?value\s*=\s*['"]?([^'">]*)`
	re := regexp.MustCompile(pattern)
	matches := re.FindStringSubmatch(content)
	if len(matches) > 1 {
		return matches[1]
	}
	return "扫描失败"
}

func validateLine(r []byte) bool {
	scanner := bufio.NewScanner(bytes.NewReader(r))
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		if line == "<title>AI-VOICE-Z01</title>" {
			return true
		}
	}
	return false
}
